package org.hiucung.libcommon.view;

import android.content.res.TypedArray;
import android.graphics.Outline;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewOutlineProvider;

import org.hiucung.libcommon.R;

import java.util.jar.Attributes;

/**
 * @author Kicc
 * @title: ViewHelper
 * @projectName OrangePPJoke
 * @description: TODO
 * @date 2021/12/28 22:28
 */
public class ViewHelper {

    public static final int RADIUS_ALL = 0;
    public static final int RADIUS_LEFT = 1;
    public static final int RADIUS_TOP = 2;
    public static final int RADIUS_RIGHT = 3;
    public static final int RADIUS_BOTTOM = 4;

    public static void setViewOutline(View view, AttributeSet attributeSet, int defStyleAttr, int defStyleRes) {
        TypedArray typedArray = view.getContext().obtainStyledAttributes(attributeSet, R.styleable.viewOutLineStrategy);
        int radius = typedArray.getDimensionPixelOffset(R.styleable.viewOutLineStrategy_clip_radius, 0);
        int radiusSide = typedArray.getDimensionPixelOffset(R.styleable.viewOutLineStrategy_clip_side, 0);

        typedArray.recycle();

        setViewOutline(view, radius, radiusSide);
    }

    public static void setViewOutline(View view, int radius, int radiusSide) {
        if (radius <= 0) {
            return;
        }

        //圆角的真正实现方式
        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                int width = view.getWidth();
                int height = view.getHeight();

                if (width <= 0 || height <= 0) {
                    return;
                }

                if (radiusSide != RADIUS_ALL) {
                    int left = 0;
                    int right = width;
                    int top = 0;
                    int bottom = height;

                    if (radiusSide == RADIUS_LEFT) {
                        right += radius;
                    } else if (radiusSide == RADIUS_TOP) {
                        bottom += radius;
                    } else if (radiusSide == RADIUS_RIGHT) {
                        left -= radius;
                    } else if (radiusSide == RADIUS_BOTTOM) {
                        top -= radius;
                    }
                    outline.setRoundRect(left, top, right, bottom, radius);
                    return;
                }

                int left = 0;
                int right = width;
                int top = 0;
                int bottom = height;
                if (radius <= 0) {
                    outline.setRect(left, top, right, bottom);
                } else {
                    outline.setRoundRect(left, top, right, bottom, radius);
                }

            }
        });
        view.setClipToOutline(radius > 0);
        view.invalidate();
    }

}
